<template>
  <el-cascader
    ref="orgCascader"
    v-model="tempOrgCode"
    style="width: 100%;"
    :options="orgTreeData"
    :props="props"
    :show-all-levels="showAllLevels"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    :size="size"
  />
</template>

<script>
import { getAuthOrgTree } from '@/api/base/common'

export default {
  name: 'OrgCascaderComponent',
  props: {
    // 父组件传来的值
    placeholder: {
      type: String,
      default: '',
      require: false
    },
    disabled: {
      type: Boolean,
      default: false,
      require: false
    },
    clearable: {
      type: Boolean,
      default: false,
      require: false
    },
    showAllLevels: {
      type: Boolean,
      default: false,
      require: false
    },
    value: {
      type: String,
      default: '',
      require: false
    },
    size: {
      type: String,
      default: '',
      require: false
    }
  },
  data() {
    return {
      currentOrgCode: '',
      orgTreeData: [],
      props: {
        multiple: false,
        // 选择任意一级选项
        checkStrictly: true,
        // 次级菜单的展开方式：click / hover
        expandTrigger: 'hover',
        // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
        emitPath: false,
        lazy: false,
        value: 'value',
        label: 'label',
        children: 'children',
        leaf: 'leaf'
      }
    }
  },
  computed: {
    tempOrgCode: {
      get() {
        return this.currentOrgCode
      },
      set(newVal) {
        const oldVal = this.currentOrgCode
        this.currentOrgCode = newVal
        this.$emit('input', newVal)
        this.$emit('change', newVal, oldVal)
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        if (this.currentOrgCode === value) {
          return
        }
        this.currentOrgCode = value
      }
    }
  },
  created() {
    this.getOrgTree()
  },
  methods: {
    getOrgTree() {
      getAuthOrgTree().then(response => {
        this.orgTreeData = response.data
      })
    }
  }
}
</script>
